package com.atguigu.day03;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Flink09_Transform_Max_MaxBy {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);
//        DataStreamSource<String> streamSource = env.readTextFile("input/sensor.txt");

        //3.通过Map将读进来的数据转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> result = streamSource.map(new MyMap());

        //4.将相同Id的数据聚合到一块
        KeyedStream<WaterSensor, Tuple> keyedStream = result.keyBy("id");

        //TODO 5.使用简单滚动聚合算子 max&maxBy
//        SingleOutputStreamOperator<WaterSensor> max = keyedStream.max("vc");
//        SingleOutputStreamOperator<WaterSensor> maxBy = keyedStream.maxBy("vc", true);
        SingleOutputStreamOperator<WaterSensor> maxBy = keyedStream.maxBy("vc", false);

        maxBy.print();

        env.execute();
    }

//    public static class MyMap implements MapFunction<String, WaterSensor>{
    public static class MyMap extends RichMapFunction<String, WaterSensor> {
    @Override
        public WaterSensor map(String value) throws Exception {

        String[] split = value.split(",");
            return new WaterSensor(split[0],Long.parseLong(split[1]),Integer.parseInt(split[2]));
        }
    }
}
